package cn.pugle.oj.leetcode;

import cn.pugle.oj.catalog.TreeProblem;

/**
 * 二叉树最长路径
 *
 * @author tzp
 * @since 2020/9/22
 */
public class LC543 implements TreeProblem {

    int max = 0;

    public int diameterOfBinaryTree(TreeNode root) {
        if (root == null || (root.left == null && root.right == null)) return 0;
        dfs(root);
        return max;
    }

    public int dfs(TreeNode node) {
        int lengthL = 0, lengthR = 0;
        if (node.left != null) lengthL = dfs(node.left) + 1;
        if (node.right != null) lengthR = dfs(node.right) + 1;
        max = Math.max(max, lengthL + lengthR);
        return Math.max(lengthL, lengthR);
    }

    public static void main(String[] args) {
        Integer[] a = {1, 2, 4, 3, 5, 7, 10, 6, null, 8, null, 11, 9, 15, null, null, null, 12, null, null, null, 13, null, null, null, null, 14};
//        Integer[] a = {1, 2, 3, 4, 5};
        TreeNode treeNode = TreeNode.arrayToTreeNode(a);
        System.out.println(new LC543().diameterOfBinaryTree(treeNode));
    }
}
